package com.chenpeijian.demo.common.until;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

public class CustomThreadPool {

    // 单例对象
    private static CustomThreadPool instance;

    // 线程池
    private ThreadPoolExecutor threadPool;

    // 私有构造方法，防止外部直接创建实例
    private CustomThreadPool() {
        int corePoolSize = 10;
        int maximumPoolSize = 50;
        long keepAliveTime = 120L;
        TimeUnit unit = TimeUnit.SECONDS;
        int capacity = 200;
        threadPool = new ThreadPoolExecutor(
                corePoolSize,
                maximumPoolSize,
                keepAliveTime,
                unit,
                new ArrayBlockingQueue<>(capacity),
                new CustomThreadFactory(),
                new CustomRejectedExecutionHandler()
        );
    }

    // 公有的静态方法，供外部获取单例对象
    public static synchronized CustomThreadPool getInstance() {
        if (instance == null) {
            instance = new CustomThreadPool();
        }
        return instance;
    }

    // 提供获取线程池的方法
    public ThreadPoolExecutor getThreadPool() {
        return threadPool;
    }
    // 自定义线程工厂
    private static class CustomThreadFactory implements java.util.concurrent.ThreadFactory {
        private final AtomicInteger threadNumber = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            Thread t = new Thread(r, "CustomThreadPool-" + threadNumber.getAndIncrement());
            if (t.isDaemon()) t.setDaemon(false);
            if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY);
            return t;
        }
    }

    // 自定义拒绝执行处理器
    private static class CustomRejectedExecutionHandler implements java.util.concurrent.RejectedExecutionHandler {
        @Override
        public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
            System.out.println("任务 " + r.toString() + " 被拒绝");
        }
    }

}